package BookManage;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 强仔
 * Date: 2022-01-18
 * Time: 15:18
 */
public class UserDao {
    //TODO 查询用户信息
    public User findUser(String name){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 1.与数据库建立连接
            connection = DBUtil.getConnection();
            // 2.构造SQL语句
            String sql = "select * from user where name = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            // 3.执行SQL语句
            resultSet = statement.executeQuery();
            // 4.遍历临时表   用户名是唯一的，所以resultSet只有一条记录或没有记录
            if(resultSet.next()){
                User user = null;
                if(resultSet.getInt("isAdmin") == 0){
                    user = new NormalUser();
                }else{
                    user = new Admin();
                }
                user.setUserId(resultSet.getInt("userId"));
                user.setName(name);
                user.setPassword(resultSet.getString("password"));
                return user;
            }else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }
}